package wcpackage.domain.dao;

import org.springframework.stereotype.Repository;
import wcpackage.domain.entities.User;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * User: rabbit
 * Date: Jun 11, 2009
 * Time: 12:34:49 AM
 */
@Repository(value = "userDAO")
public class UserDAOImpl extends AbstractDAO<User, Long> implements UserDAO {

    @PersistenceContext
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public Class<User> getClazz() {
        return User.class;
    }

    public User findByLoginAndPassword(String login, String password) {
        TypedQuery<User> query = entityManager.createNamedQuery("User.findByLoginAndPassword", User.class);
        query.setParameter("login", login);
        query.setParameter("password", password);
        List<User> users = query.getResultList();
        return users.size() == 0 ? null : users.get(0);
    }

    public User findByLogin(String login) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery c = cb.createQuery(User.class);
        Root user = c.from(User.class);
        c.select(user).where(cb.equal(user.get("login"), login));
        TypedQuery<User> q = entityManager.createQuery(c);
        return q.getSingleResult();
    }

}
